<template>
  <div class="share-panel-content"
       v-show="delayShow">
    <img :src="shareImgSrc"
         class="popup-img"
         v-show="showPanel && shareImgSrc" />
    <!-- 分享弹窗 -->
    <van-popup v-model="showPanel"
               round
               closeable
               position="bottom"
               class="popup-share">
      <!-- 标题 -->
      <page-bottom class="popup-title"
                   :more="false"
                   noMoreText="分享到">
      </page-bottom>
      <div class="share-action flex justify-center">
        <div class="action-item"
             v-clipboard:copy="shareLink"
             v-clipboard:success="onCopySuccess"
             v-clipboard:error="onCopyError">
          <div class="action-item-icon link-icon"></div>
          <div>复制链接</div>
        </div>

        <div class="action-item"
             @click="$toast({message:'请长按海报保存',type:'loading'})">
          <div class="action-item-icon save-icon"></div>
          <div>保存图片</div>
        </div>
      </div>
    </van-popup>

    <!-- canvas -->
    <canvas width="930"
            height="1200"
            ref="shareCanvas"
            class="hideBox"></canvas>
  </div>
</template>

<script>
import PageBottom from '@/components/PageBottom'
import VueClipboard from 'vue-clipboard2'
import Vue from 'vue'
// 画布对象
var canvasObj = null
var ctx = null
// 跨域图片处理
var imgObj = {
  shareBgObj: new Image(),
  qrImgObj: new Image()
}
imgObj.shareBgObj.setAttribute('crossOrigin', 'Anonymous')
imgObj.qrImgObj.setAttribute('crossOrigin', 'Anonymous')
export default {
  name: 'SharePopup',
  data() {
    return {
      showPanel: false, // 显示弹窗
      delayShow: false, // 整体延迟隐藏
      errorMsg: null, // 错误消息
      shareImgSrc: null // 分享的图片url
    }
  },
  created() {
    this.showPanel = this.show
    this.delayShow = this.show
    Vue.use(VueClipboard)
  },
  mounted() {
    this.initCanvasImg()
      .then(res => {
        // 清空旧的错误消息
        this.errorMsg = null
        this.drawCanvas()
      })
      .catch(res => {
        // 存储错误消息，提示
        this.errorMsg = res.message
        this.showPanel &&
          this.$toast({ type: 'loading', messaage: this.errorMsg })
      })
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    // 分享的链接配置
    shareLink: {
      type: String,
      default: window.location.href
    }
  },
  components: {
    PageBottom
  },
  watch: {
    /**
     * 父组件传递过来的值改变
     * 联动组件内的show进行显示
     */
    show(newVal, oldVal) {
      this.showPanel = newVal
      if (!newVal) {
        setTimeout(() => {
          this.delayShow = newVal
        }, 300)
      } else {
        this.delayShow = newVal
        this.errorMsg &&
          this.$toast({ type: 'loading', messaage: this.errorMsg })
      }
    },
    /**
     * 监听组件内的状态修改
     * 然后触发父页面的状态修改
     */
    showPanel(newVal, oldVal) {
      this.$emit('clickMask', newVal)
    }
  },
  /**
   * v-model绑定对应的方法，和修改的方法
   */
  model: {
    prop: 'show',
    event: 'clickMask'
  },
  methods: {
    /**
     * 初始化图片
     */
    initCanvasImg() {
      // 获取图片分享的连接
      let link = `${window.location.origin}${window.location.pathname}`
      let imgList = [
        {
          obj: 'shareBgObj',
          src: require('@/assets/image/share-bg.png'),
          srcDesc: '分享背景图'
        },
        {
          obj: 'qrImgObj',
          src: '/home/qrcode?url=' + encodeURIComponent(link),
          srcDesc: '分享二维码'
        }
      ]
      return Promise.all(
        imgList.map(item => {
          return new Promise((resolve, reject) => {
            imgObj[item.obj].onload = function() {
              resolve({ message: '加载成功' })
            }
            imgObj[item.obj].onerror = function() {
              reject(new Error(`${item.srcDesc}加载失败`))
            }
            imgObj[item.obj].src = item.src
          })
        })
      )
    },

    /**
     * 渲染canvas
     */
    drawCanvas() {
      // 初始化画布对象
      canvasObj = this.$refs.shareCanvas
      ctx = canvasObj.getContext('2d')
      // 背景
      ctx.fillStyle = '#ffffff'
      ctx.fillRect(0, 0, 930, 1200)
      // 分享背景图
      ctx.drawImage(imgObj.shareBgObj, 0, 0, 930, 930)
      // 分享语句
      ctx.fillStyle = '#666666'
      ctx.font = '44px sans-serif'
      ctx.fillText('精美礼品免费领  火爆进行中...', 46, 1080)
      // 拓客二维码
      ctx.drawImage(imgObj.qrImgObj, 676, 966, 200, 200)

      this.shareImgSrc = canvasObj.toDataURL()
      ctx.clearRect(0, 0, 930, 1200) // 清空画布
    },

    /**
     * 复制错误
     */
    onCopyError() {
      this.$toast({
        type: 'fail',
        message: '复制失败，请重试'
      })
    },
    /**
     * 复制错误
     */
    onCopySuccess() {
      this.$toast({
        type: 'success',
        message: '复制成功！快去分享把'
      })
    }
  }
}
</script>

<style lang="scss">
.share-panel-content {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: 300;
  .popup-share {
    .popup-title {
      height: 60px;
      .text {
        font-size: 16px;
        color: #333333;
      }
    }
    /deep/ .van-popup__close-icon--top-right {
      top: 20px;
    }
  }
  .popup-img {
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 3000;
    width: 233px;
    border-radius: 5px;
  }

  .share-action {
    .action-item {
      width: 115px;
      height: 105px;
      text-align: center;
      font-size: 12px;
      color: #666666;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      .action-item-icon {
        width: 52px;
        height: 52px;
        margin-bottom: 1px;
        background-repeat: no-repeat;
        background-size: 100% 100%;
        position: relative;
        &.link-icon {
          background-image: url('../../assets/image/share_icon_link.png');
        }
        &.save-icon {
          background-image: url('../../assets/image/share_icon_img.png');
        }
      }
      &:active {
        background-color: #f9f9f9;
      }
    }
  }
  .hideBox {
    display: none;
  }
}
</style>
